<?php
/**
 * Client.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-22
 * Time: 16:38
 */

namespace App\OSS;


use OSS\Core\OssException;
use OSS\OssClient;

class Client
{
    private $accessKeyId  = null;
    private $accessKeySecret  = null;
    private $endPoint = 'http://oss-cn-hangzhou.aliyuncs.com';
    private $client = null;

    const BUCKET_IMG_NAME = 'tiaofu-img';
    const BUCKET_FILE_NAME = 'tiaofu-file';

    // 杭州外网 oss-cn-hangzhou.aliyuncs.com
    // 杭州内网 oss-cn-hangzhou-internal.aliyuncs.com
    // 列表 https://help.aliyun.com/document_detail/31837.html?spm=a2c4g.11186623.6.624.14852137FtVWkU
    public function __construct()
    {
        $this->accessKeyId = env('OSS_ACCESS_KEY_ID', null);
        $this->accessKeySecret = env('OSS_ACCESS_KEY_SECRET', null);
        $this->endPoint = env('OSS_END_POINT', 'http://oss-cn-hangzhou.aliyuncs.com');
        $this->client = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endPoint);
    }

    public function createBucket($name)
    {
        try {
            $options = [ OssClient::OSS_STORAGE => OssClient::OSS_STORAGE_STANDARD];
            $this->client->createBucket($name, OssClient::OSS_ACL_TYPE_PUBLIC_READ, $options);
        } catch(OssException $e) {
            \Log::error("[OSS ERROR]:".__FUNCTION__.'->'.$e->getMessage());
            return false;
        }
        return true;
    }

    public function getBucketList()
    {
        try{
            $bucketListInfo = $this->client->listBuckets();
        } catch(OssException $e) {
            \Log::error("[OSS ERROR]:".__FUNCTION__.'->'.$e->getMessage());
            return [];
        }
        $bucketList = $bucketListInfo->getBucketList();
        $r = [];
        foreach($bucketList as $bucket) {
            $r[] = [
                'location' => $bucket->getLocation(),
                'name' => $bucket->getName(),
                'createDate' => $bucket->getCreateDate()
            ];
        }
        return $r;
    }

    public function uploadFile($bucket, $fileName, $filePath)
    {
        try {
            $data = $this->client->uploadFile($bucket, $fileName, $filePath);
        } catch (OssException $e) {
            \Log::error("[OSS ERROR]:".__FUNCTION__.'->'.$e->getMessage());
            return false;
        }
        return $data['info']['url'] ?? false;
        /*
    array:15 [
  "server" => "AliyunOSS"
  "date" => "Tue, 22 Dec 2020 09:09:12 GMT"
  "content-length" => "0"
  "connection" => "keep-alive"
  "x-oss-request-id" => "5FE1B7B70BC3D9343736BF31"
  "etag" => ""A04B3E1E7EBF9E6E9FA3218262650CFC""
  "x-oss-hash-crc64ecma" => "15649738149816421656"
  "content-md5" => "oEs+Hn6/nm6foyGCYmUM/A=="
  "x-oss-server-time" => "68"
  info" => array:27 [▼
    "url" => "http://tiaofu-img.oss-cn-hangzhou.aliyuncs.com/test/abcde.jpg"
    "content_type" => null
    "http_code" => 200
    "header_size" => 310
    "request_size" => 399
    "filetime" => -1
    "ssl_verify_result" => 0
    "redirect_count" => 0
    "total_time" => 0.18467
    "namelookup_time" => 0.060374
    "connect_time" => 0.090766
    "pretransfer_time" => 0.091258
    "size_upload" => 25448.0
    "size_download" => 0.0
    "speed_download" => 0.0
    "speed_upload" => 137802.0
    "download_content_length" => 0.0
    "upload_content_length" => 25448.0
    "starttransfer_time" => 0.091267
    "redirect_time" => 0.0
    "redirect_url" => ""
    "primary_ip" => "118.31.219.217"
    "certinfo" => []
    "primary_port" => 80
    "local_ip" => "10.0.2.15"
    "local_port" => 32809
    "method" => "PUT"
  ]
  "oss-request-url" => "http://tiaofu-img.oss-cn-hangzhou.aliyuncs.com/test/abcde.jpg"
  "oss-redirects" => 0
  "oss-stringtosign" => """
    PUT

    image/jpeg
    Tue, 22 Dec 2020 09:09:07 GMT
    /tiaofu-img/test/abcde.jpg
    """
  "oss-requestheaders" => array:5 [▶]
  "body" => ""
]
         *
         *
         */
    }

    public function upBase64Img($base64)
    {
        $base64 = preg_replace('/^data:image\/(\w)+;base64,/', '', $base64);
        $fileName = implode('.',[md5(md5($base64).md5(microtime())), 'jpg']);
        $filePath = '/tmp/'.$fileName;
        $url = '';
        $ok = file_put_contents($filePath, base64_decode($base64));
        if($ok > 0) {
            $upName = implode('/', [date('Y'), date('m')]).'/'.$fileName;
            $url =$this->uploadFile(self::BUCKET_IMG_NAME, $upName, $filePath);
        }
        return $url;
    }

}